package com.humingzhang.client.factory;

import com.humingzhang.client.FileClient;
import com.humingzhang.client.FileConfig;
import com.humingzhang.client.aws.AwsConfig;
import com.humingzhang.client.aws.AwsFileClient;
import com.humingzhang.client.fastdfs.FastDfsConfig;
import com.humingzhang.client.fastdfs.FastDfsFileClient;
import com.humingzhang.client.ftp.FtpConfig;
import com.humingzhang.client.ftp.FtpFileClient;
import com.humingzhang.client.oss.OssConfig;
import com.humingzhang.client.oss.OssFileClient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件存储工厂类
 *
 * @author minghu.zhang
 */
public class FileClientFactory {

    /**
     * 配置类映射
     */
    private static final Map<Class<? extends FileConfig>, Class<? extends FileClient>>
            CLIENT_CLASS_MAPPER = new HashMap<>();

    /*
     * 注册客户端
     */
    static {
        CLIENT_CLASS_MAPPER.put(AwsConfig.class, AwsFileClient.class);
        CLIENT_CLASS_MAPPER.put(FastDfsConfig.class, FastDfsFileClient.class);
        CLIENT_CLASS_MAPPER.put(FtpConfig.class, FtpFileClient.class);
        CLIENT_CLASS_MAPPER.put(OssConfig.class, OssFileClient.class);
    }

    /**
     * 创建存储客户端
     *
     * @param config 客户端配置对象
     * @return 存储客户端
     */
    public static FileClient createClient(FileConfig config) {
        try {
            Class<? extends FileClient> clientClass = CLIENT_CLASS_MAPPER.get(config.getClass());
            Constructor<? extends FileClient> constructor = clientClass.getConstructor(config.getClass());
            return constructor.newInstance(config);
        } catch (Exception e) {
            throw new RuntimeException("存储客户端创建失败", e);
        }
    }

}
